package com.c611.smartclassroom.service.Impl;

import com.c611.smartclassroom.dto.ScheduleDto;
import com.c611.smartclassroom.mapper.ScheduleMapper;
import com.c611.smartclassroom.model.Schedule;
import com.c611.smartclassroom.model.ScheduleExample;
import com.c611.smartclassroom.service.ScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class ScheduleServiceImpl implements ScheduleService {


    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    ScheduleMapper scheduleMapper;

    @Cacheable(value = "schedule",key = "'querySchByClass::' + #classId + '::' + #semesterID",unless = "#result == null ")
    @Override
    public List<ScheduleDto> querySchByClass(String classId, String semesterID) {
        List<ScheduleDto> scheduleDtos = new ArrayList<>();

        List<Schedule> scheds = null;
        for(int i = 1;i <= 10;i++) {
            ScheduleExample scheduleExample = new ScheduleExample();
            scheduleExample.createCriteria().andClassroomidEqualTo(classId).andSemesteridEqualTo(semesterID).andLessonEqualTo(i).andDelflagNotEqualTo(1);
            //第一节课的所有对象
            scheds = scheduleMapper.selectByExample(scheduleExample);
            //对一节课的Dto
            ScheduleDto scheduleDto = new ScheduleDto();
            scheduleDto.setLessonName("第" + i + "节课");
            for (Schedule sched : scheds) {
                String info = null;
                switch (sched.getWeek()) {
                    case 1:
                        info = sched.getCoursename() + "\n"
                                + sched.getTeachername() + "\n"
                                + sched.getScheduleid() +
                                "（"  + sched.getWeekseq() + "周）\n"
                                + sched.getClassname() + "\n"
                                + (sched.getRemark() == null ? "" : sched.getRemark());
                        scheduleDto.setMonDay(info);
                        break;
                    case 2:
                        info = sched.getCoursename() + "\n"
                                + sched.getTeachername() + "\n"
                                + sched.getScheduleid() +
                                "（"  + sched.getWeekseq() + "周）\n"
                                + sched.getClassname() + "\n"
                                + (sched.getRemark() == null ? "" : sched.getRemark());
                        scheduleDto.setTuesDay(info);
                        break;
                    case 3:
                        info = sched.getCoursename() + "\n"
                                + sched.getTeachername() + "\n"
                                + sched.getScheduleid() +
                                "（"  + sched.getWeekseq() + "周）\n"
                                + sched.getClassname() + "\n"
                                + (sched.getRemark() == null ? "" : sched.getRemark());
                        scheduleDto.setWednesDay(info);
                        break;
                    case 4:
                        info = sched.getCoursename() + "\n"
                                + sched.getTeachername() + "\n"
                                + sched.getScheduleid() +
                                "（"  + sched.getWeekseq() + "周）\n"
                                + sched.getClassname() + "\n"
                                + (sched.getRemark() == null ? "" : sched.getRemark());
                        scheduleDto.setThursDay(info);
                        break;
                    case 5:
                        info = sched.getCoursename() + "\n"
                                + sched.getTeachername() + "\n"
                                + sched.getScheduleid() +
                                "（"  + sched.getWeekseq() + "周）\n"
                                + sched.getClassname() + "\n"
                                + (sched.getRemark() == null ? "" : sched.getRemark());
                        scheduleDto.setFriDay(info);
                        break;
                    case 6:
                        info = sched.getCoursename() + "\n"
                                + sched.getTeachername() + "\n"
                                + sched.getScheduleid() +
                                "（"  + sched.getWeekseq() + "周）\n"
                                + sched.getClassname() + "\n"
                                + (sched.getRemark() == null ? "" : sched.getRemark());
                        scheduleDto.setSaturDay(info);
                        break;
                    case 7:
                        info = sched.getCoursename() + "\n"
                                + sched.getTeachername() + "\n"
                                + sched.getScheduleid() +
                                "（"  + sched.getWeekseq() + "周）\n"
                                + sched.getClassname() + "\n"
                                + (sched.getRemark() == null ? "" : sched.getRemark());
                        scheduleDto.setSunDay(info);
                        break;
                }
            }
//            System.out.println("第" + i + "节课的课表：" + scheduleDto);
            scheduleDtos.add(scheduleDto);
        }
        return scheduleDtos;
    }

    @CacheEvict(value = "schedule",allEntries = true)
    @Override
    public void importSchExcel(List<ScheduleDto> personList, String classId, String semesterId) {
        //1,遍历出每个Dto对象(即第一节课，第二节课的对象)
        for (int lesson = 1;lesson <= 10;lesson++) {
            //填写周一课表

            for(int week = 1;week <= 7;week++) {
                String infoDay = null;

                if(week == 1) infoDay = personList.get(lesson - 1).getMonDay();
                if(week == 2) infoDay = personList.get(lesson - 1).getThursDay();
                if(week == 3) infoDay = personList.get(lesson - 1).getTuesDay();
                if(week == 4) infoDay = personList.get(lesson - 1).getWednesDay();
                if(week == 5) infoDay = personList.get(lesson - 1).getThursDay();
                if(week == 6) infoDay = personList.get(lesson - 1).getSaturDay();
                if(week == 7) infoDay = personList.get(lesson - 1).getSunDay();

                if(infoDay != null) {
                    Schedule schedule = new Schedule();
                    String replaceInfoDay = infoDay
                            .replaceAll(",","，")
                            .replaceAll("\n","，")
                            .replaceAll("周","")
                            .replaceAll(" ","")
                            .replaceAll("\\(","，")
                            .replaceAll("\\)","")
                            .replaceAll("（","，")
                            .replaceAll("）","");
                    String info[] = replaceInfoDay.split("，");
                    if(info.length >= 5) {
                        schedule.setCoursename(info[0]);
                        schedule.setTeachername(info[1]);
                        schedule.setScheduleid(Integer.parseInt(info[2]));
                        schedule.setWeekseq(info[3]);
                        //有[或者【说明是合班
                        if(info[4].contains("[")) {
//                            System.out.println("有合班数据===========================================");
                            int indexStart = infoDay.indexOf('[');
                            int indexEnd = infoDay.lastIndexOf(']');
                            schedule.setClassname(infoDay.substring(indexStart + 1,indexEnd));
                            if(info[info.length - 1].charAt(info[info.length - 1].length() -1) != ']')
                                schedule.setRemark(info[info.length - 1]);
                        }else if (info[4].contains("【")) {
                            int indexStart = infoDay.indexOf('【');
                            int indexEnd = infoDay.lastIndexOf('】');
                            schedule.setClassname(infoDay.substring(indexStart + 1,indexEnd));
                            if(info[info.length - 1].charAt(info[info.length - 1].length() -1) != '】')
                                schedule.setRemark(info[info.length - 1]);
                        }else {
                            schedule.setClassname(info[4]);
                            if(info.length == 6) schedule.setRemark(info[5]);
                        }
                        schedule.setClassroomid(classId);
                        schedule.setSemesterid(semesterId);
                        schedule.setWeek(week);
                        schedule.setLesson(lesson);
                    }

                    //插入前判断该课表中相同学期，相同教室，相同周，相同节课，未置废的标识中有无课
                    ScheduleExample scheduleExample = new ScheduleExample();
                    scheduleExample.createCriteria()
                            .andSemesteridEqualTo(semesterId)
                            .andClassroomidEqualTo(classId)
                            .andLessonEqualTo(lesson)
                            .andWeekEqualTo(week)
                            .andDelflagNotEqualTo(1);
                    long flag = scheduleMapper.countByExample(scheduleExample);
                    //有的化将以前的标置废，重新插入
                    Schedule param1 = new Schedule();
                    param1.setDelflag(1);
//                    System.out.println("==================================================");
//                    System.out.println(flag);
                    if(flag != 0) {
//                        System.out.println("================================================================================");
                        scheduleMapper.updateByExampleSelective(param1,scheduleExample);
                    }
                    //重新插入
                    scheduleMapper.insertSelective(schedule);
                }
            }
        }

    }

}
